﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;

namespace SiteMapService
{
    class Class
    {
    }

    public class SiteMap
    {
        public static void CreateSiteMap()
        {
            DateTime SiteDate = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0));
            string conn = ConfigurationManager.ConnectionStrings["DB_ConnectionString"].ConnectionString;
            string ServerID = ConfigurationManager.AppSettings["ServerID"];
            string UserID = ConfigurationManager.AppSettings["UserID"];
            string Password = ConfigurationManager.AppSettings["Password"];
            string DataBase = ConfigurationManager.AppSettings["DataBase"];
            string sql = ConfigurationManager.AppSettings["MySql"];

            conn = string.Format(conn, ServerID, QT.Security.AESHelper.AESDecrypt(UserID), QT.Security.AESHelper.AESDecrypt(Password), DataBase);
            DataTable dt = new QT.DBO.SqlDBHelper(conn).DataTable(sql);
                        
            string LogPath = Environment.CurrentDirectory + @"\logs";
            string SiteMapPath = ConfigurationManager.AppSettings["SitePath"].Replace("%Y", SiteDate.Year.ToString()).Replace("%M", SiteDate.Month.ToString().PadLeft(2, '0')).Replace("%D", SiteDate.Day.ToString().PadLeft(2, '0'));
            string SiteMapURIPath = ConfigurationManager.AppSettings["SiteURIPath"].Replace("%Y", SiteDate.Year.ToString()).Replace("%M", SiteDate.Month.ToString().PadLeft(2, '0')).Replace("%D", SiteDate.Day.ToString().PadLeft(2, '0'));
            string SiteIndexPath = ConfigurationManager.AppSettings["SiteIndexPath"];
            string xmlns = ConfigurationManager.AppSettings["XMLns"];
            
            Tools.outLog(LogPath, "开始生成站点地图");

            #region SiteMap

            if (File.Exists(SiteMapPath))
            {
                Tools.outLog(LogPath, "站点地图已存在，本次操作取消");
                return;
            }

            XmlDocument doc = new XmlDocument();
            XmlElement root = null;
            string NameSpace = "";

            try
            {
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(dec);
                //创建一个根节点（一级）
                root = doc.CreateElement("urlset");
                if (!string.IsNullOrEmpty(xmlns)) root.SetAttribute("xmlns", xmlns);
                doc.AppendChild(root);

                foreach (DataRow dr in dt.Rows)
                {
                    XmlNode node = doc.CreateElement("url");

                    XmlElement loc = doc.CreateElement("loc");
                    loc.InnerText = dr[0].ToString();
                    node.AppendChild(loc);
                    
                    XmlElement lastmod = doc.CreateElement("lastmod");
                    lastmod.InnerText = SiteDate.ToString("yyyy-MM-dd");
                    node.AppendChild(lastmod);

                    XmlElement changefreq = doc.CreateElement("changefreq");
                    changefreq.InnerText = dr["Frequency"].ToString();
                    node.AppendChild(changefreq);

                    XmlElement priority = doc.CreateElement("priority");
                    priority.InnerText = dr["Priority"].ToString(); ;
                    node.AppendChild(priority);

                    root.AppendChild(node);
                }

                doc.Save(SiteMapPath);
            }
            catch (Exception ex)
            {
                Tools.outLog(LogPath, ex.Message);
                return;
            }

            #endregion

            #region SiteIndex

            doc = new XmlDocument();

            try
            {
                if (!File.Exists(SiteIndexPath))
                {
                    XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    doc.AppendChild(dec);
                    //创建一个根节点（一级）
                    root = doc.CreateElement("sitemapindex");
                    if (!string.IsNullOrEmpty(xmlns)) root.SetAttribute("xmlns", xmlns);
                    doc.AppendChild(root);
                }
                else
                {
                    doc.Load(SiteIndexPath);
                    NameSpace = doc.DocumentElement.NamespaceURI;
                    XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
                    xnm.AddNamespace("nm", NameSpace);

                    root = (XmlElement)doc.SelectSingleNode("nm:sitemapindex", xnm);
                }

                XmlNode node = doc.CreateElement("sitemap", NameSpace);

                XmlElement loc = doc.CreateElement("loc", NameSpace);
                loc.InnerText = SiteMapURIPath;
                node.AppendChild(loc);

                XmlElement lastmod = doc.CreateElement("lastmod", NameSpace);
                lastmod.InnerText = DateTime.Now.ToString("yyyy-MM-dd");
                node.AppendChild(lastmod);

                root.AppendChild(node);
                doc.Save(SiteIndexPath);
            }
            catch (Exception ex)
            {
                Tools.outLog(LogPath, ex.Message);
                return;
            }

            #endregion

            Tools.outLog(LogPath, "站点地图生成完成");
        }
    }

    public class Tools
    {
        public static void outLog(string txtPath,string txt)
        {
            if (!Directory.Exists(txtPath)) Directory.CreateDirectory(txtPath);

            FileStream fs = new FileStream(txtPath + @"\" + DateTime.Now.ToString("yyyy-MM") + @".log", FileMode.Append, FileAccess.Write, FileShare.Read);
            StreamWriter text = new StreamWriter(fs);
            text.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + txt);
            text.Flush();
            fs.Close();
        }
    }
}
